﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Logger
{
    public class Logger : IDisposable
    {

        #region Private Fields

        private string _logFilePath;
        private bool _started = false;
        private StreamWriter _writer;
        private string _logTitle;

        #endregion


        #region Constructors

        public Logger(string logFilePath) {
            _logFilePath = logFilePath;
        }

        #endregion

        
        #region Public Methods

        public void Start(string logTitle) {
            _writer = new StreamWriter(_logFilePath, true);
            _logTitle = logTitle;
            _writer.WriteLine();
            _writer.WriteLine();
            _writer.WriteLine(string.Format("{1} : Logging for '{0}' started ---------------------------.", logTitle, Now()));
            _started = true;
        }

        public void Log(string message) {
            if (!_started) {
                throw new InvalidOperationException("You have to start the logger by executing its Start() method before you can log messages!.");
            }
            if (message == null) {
                throw new ArgumentNullException("The message to log can't be 'null'!.");
            }
            _writer.WriteLine(string.Format("{0} : {1}.", Now(), message));
        }

        #endregion


        #region Private Methods

        private string Now() {
            return DateTime.Now.ToString("dd.MM.yyyy HH:mm", CultureInfo.InvariantCulture);
        }


        private void Stop() {
            _writer.WriteLine(string.Format("{0} : Logging for '{1}' stopped ---------------------------.", Now(), _logTitle));
        }

        public void Dispose() {
            if (_writer != null) {
                Stop();
                _writer.Dispose();
            }
        }
        #endregion

        
    }
}
